const Koa = require('koa');
const app = new Koa();
const router = require("koa-router")();
const bodyparser = require('koa-bodyparser');
const session = require('koa-session');
const { login, registry , updata } = require("./server/mysql")
//验证码
let svgCaptcha = require('svg-captcha');

router.get("/captch",(ctx,next)=>{
        let captcha = svgCaptcha.create({
            size: 4,
            width: 100,
            height: 40,
        })
        ctx.session.captcha = captcha.text.toLowerCase();
        console.log(ctx.session.captcha);
        ctx.type = "svg"
        ctx.body = captcha.data;
})

router.post("/login", async (ctx, next) => {
    const { name, pwd } = ctx.request.body;
    const userCaptcha = ctx.session.captcha;
    console.log(userCaptcha);
    const res = await login(`select * from sun where name="${name}" and pwd='${pwd}' `);
    if (res.length > 0) {
        ctx.body = {
            code: 200,
            msg: "登录成功",
            res,
        }
    } else {
        ctx.body = {
            code: 401,
            msg: "等绿失败，用户名或密码错误",
            res
        }
    }
});


router.post("/registry", async (ctx, next) => {
    const { name, pwd } = ctx.request.body;
    console.log(name, pwd);
    const res = await login(`select * from sun where name="${name}"`);
    if (!res.length>0) {
        await registry(`INSERT INTO sun(name,pwd) VALUES('${name}','${pwd}')`)
        ctx.body = {
            code: 200,
            msg: "注册成功",
        }
    }else{
        ctx.body = {
            code: 401,
            msg: "注册失败,用户名已存在",
        }
    }
});

router.post("/updata", async (ctx, next) => {
    const { name, pwd } = ctx.request.body;
    console.log(name, pwd);
    const res = await login(`select * from sun where name="${name}"`);
    console.log(res);
    if (res.length>0) {
        await updata(`UPDATE sun SET pwd = '${pwd}' where id='${res[0].id}'`)
        ctx.body = {
            code: 200,
            msg: "修改成功",
            res
        }
    }else{
        ctx.body = {
            code: 401,
            msg: "修改失败,用户名不存在",
        }
    }
});






app.use(bodyparser());
app.keys = ['xiaohuang'];
app.use(session({}, app));
app.use(router.routes(), router.allowedMethods());
app.listen(3000);